#include "utils.h"
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QString>
#include <QFile>
#include <QDir>
#include <QtCore/QGlobal.h>
#include "httpmgr.h"
#include <QProcess>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

//判断字符串是否全为数字
bool isNumeric(const QString &str) {
    for (QChar ch : str) {
        if (!ch.isDigit()) {
            return false;
        }
    }
    return true;
}

//判断字符串是否是符合QQ邮箱的格式
bool isQQEmail(const QString &email) {
    QRegularExpression emailRegex(R"(^[0-9a-zA-Z_\-\.\+]+@[0-9a-zA-Z_\-\.\+]+\.(com|cn|net|org|vip|cloud|gov|hk|tw)$)");

    // 执行验证
    QRegularExpressionMatch match = emailRegex.match(email);

    // 如果找到匹配项，则验证成功
    return match.hasMatch();

}

QByteArray readBytesFile(const QString& filePath,const QString& fileName)
{
    QFile file(filePath+fileName);
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "无法打开文件: " << filePath+fileName;
            return QByteArray();
    }
    QByteArray bytes = file.readAll();
    file.close();
    return bytes;
}

void saveBytesFile(const QString& filePath,const QString& fileName,const QByteArray& pictureByteArray)
{
    QString relativeFilePath = QDir::currentPath() + QDir::separator() + filePath + fileName;

    QFileInfo fileInfo(relativeFilePath);
    QDir dir = fileInfo.absoluteDir();
    if (!dir.exists())
    {
            // 如果目录不存在，则创建目录，此处使用mkpath可以创建多级目录（包含中间缺失的目录）
            if (dir.mkpath("."))
            {
            qDebug() << "目录创建成功" << filePath;
            }
            else
            {
            qDebug() << "创建目录时出错"<< filePath;
            return;
            }
    }

    QFile file(relativeFilePath);
    if (file.open(QIODevice::WriteOnly))
    {
            // 将字节数组数据写入文件
            qint64 bytesWritten = file.write(pictureByteArray);
            file.close();
            if (bytesWritten == pictureByteArray.size())
            {
            //qDebug() << "图片保存成功" <<fileName;
            return ;
            }
            else
            {
            qDebug() << "写入文件时出错" << "saveBytesFile utils";
            return ;
            }
    }
}

void getImageFromServer(const QString &avatar)
{
    QJsonObject json_obj;
    json_obj["AvatarName"] = avatar;
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/toGetImage"),
                                        json_obj, ReqId::ID_REG_USER,Modules::REGISTERMOD);

}



void untarFile(const QString& tarFilePath, const QString& destDir) {
    // 检查目标目录是否存在，如果不存在则创建
    QDir dir;
    if (!dir.exists(destDir)) {
            if (!dir.mkpath(destDir)) {
            qDebug()<< "mkdir error";
            return;
            }
    }

    QProcess process;
    QStringList args;
    args << "-xf" << tarFilePath << "-C" << destDir;
    process.start("tar", args);
    process.waitForFinished();
}

int getAnotherUserId(const QString &msgStr, const int &knownUserId)
{
    QString id = QString::number(knownUserId);
    // 去除 "msg_" 前缀
    QString idPart = msgStr.mid(4);

    // 使用 "_" 分割字符串
    QStringList idList = idPart.split("_");

    // 检查分割后的列表长度是否为 2
    if (idList.size() == 2) {
            if (idList[0] == id) {
            return idList[1].toInt();
            } else if (idList[1] == id) {
            return idList[0].toInt();
            }
    }

    // 如果没有匹配到，提示错误
    qDebug()<<"getAnotherUserId函数查询失败:"<<msgStr,id;
}
QStringList getContactDataById(int friendId) {
    QStringList contactData;

    const QString connectionName = "init";
    QSqlDatabase db;
    if (QSqlDatabase::contains(connectionName)) {
            db = QSqlDatabase::database(connectionName);
            if (!db.isOpen()) {
            if (!db.open()) {
                qDebug() << "无法打开已存在的数据库连接:" << db.lastError().text();
                    return contactData;
            }
            }
    } else {
            db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
            QString databasePath = USER_PATH + "user.db";
            db.setDatabaseName(databasePath);
            if (!db.open()) {
            qDebug() << "无法打开新的数据库连接:" << db.lastError().text();
                return contactData;
            }
    }
    QSqlQuery query(db);
    query.prepare("SELECT friend_id, name, email, avatar FROM contacts WHERE friend_id = :friend_id");
    query.bindValue(":friend_id", friendId);

    if (!query.exec()) {
            qDebug() << "执行查询时出错:getContactDataById" << query.lastError().text();
                                                 db.close();
            return contactData;
    }

    if (query.next()) {
            contactData<< query.value(0).toString();
            contactData<< query.value(1).toString();
            contactData<< query.value(2).toString();
            contactData<< query.value(3).toString();
    }

    db.close();
    return contactData;
}


bool updateReadTime(const QString &msgId, double max_score, int msgNums)
{
    const QString connectionName = "write";
    QSqlDatabase db;
    if (QSqlDatabase::contains(connectionName)) {
            db = QSqlDatabase::database(connectionName);
            if (!db.isOpen()) {
                if (!db.open()) {
                    qDebug() << "无法打开已存在的数据库连接:" << db.lastError().text();
                        return false;
                }
            }
    } else {
            db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
            QString databasePath = USER_PATH + "user.db";
            db.setDatabaseName(databasePath);
            if (!db.open()) {
                qDebug() << "无法打开新的数据库连接:" << db.lastError().text();
                    return false;
            }
    }

    // 开始事务
    if (!db.transaction()) {
            qDebug() << "无法开始事务:" << db.lastError().text();
                                                 return false;
    }

    // 遍历查询结果并更新 ReadTime
    // 获取当前时间戳（秒级）
    double currentTimestamp = QDateTime::currentSecsSinceEpoch();
    QSqlQuery updateDataQuery(db);
    QString updateQuery = "UPDATE messages SET ReadTime  = :readtime WHERE "
                          "msgId = :msgId AND score = :score";
    updateDataQuery.prepare(updateQuery);
    double min_score = max_score - msgNums +1;
    for(int i=max_score;i>=min_score;i--){
        // 构造更新 SQL 语句
        updateDataQuery.bindValue(":readtime", currentTimestamp);
        updateDataQuery.bindValue(":msgId", msgId);
        updateDataQuery.bindValue(":score", i);
        // 执行更新
        if (!updateDataQuery.exec()) {
            qDebug() << "更新数据失败:" << updateDataQuery.lastError().text();
            db.rollback(); // 回滚事务
            return false;
        }
    }

    // 提交事务
    if (!db.commit()) {
            qDebug() << "无法提交事务:" << db.lastError().text();
                                                     db.rollback(); // 回滚事务
            return false;
    }

    QJsonObject json_obj;
    json_obj["MsgId"] = msgId;
    json_obj["max_score"] = max_score;
    json_obj["min_score"] = min_score;
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/UpdataReadTime"),
                                        json_obj, ReqId::ID_CHAT_UPREADTIME,Modules::CHATMOD);

    return true;
}

QStringList queryMsgByMsgIdAndScore(QString msgId, double score)
{
    const QString connectionName = "read";
    QSqlDatabase db;
    QStringList msgData;

    // 检查数据库连接是否已存在
    if (QSqlDatabase::contains(connectionName)) {
            db = QSqlDatabase::database(connectionName);
            if (!db.isOpen()) {
            if (!db.open()) {
                        qDebug() << "无法打开已存在的数据库连接:" << db.lastError().text();
                            return msgData;
            }
            }
    } else {
            // 添加新的数据库连接
            db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
            QString databasePath = USER_PATH + "user.db";
            db.setDatabaseName(databasePath);
            if (!db.open()) {
            qDebug() << "无法打开新的数据库连接:queryMsgByMsgIdAndScore" << db.lastError().text();
                return msgData;
            }
    }

    // 开始事务
    db.transaction();

    // 准备查询语句
    QSqlQuery query(db);
    query.prepare("SELECT TargetId, Type, Media, Content FROM "
                  "messages WHERE msgId = :msg_id AND score = :score");
    query.bindValue(":msg_id", msgId);
    query.bindValue(":score", score);

    // 执行查询
    if (!query.exec()) {
            qDebug() << "执行查询时出错: queryMsgByMsgIdAndScore" << query.lastError().text();
                                                                                // 回滚事务
                                                                                db.rollback();
            db.close();
            return msgData;
    }

    if (query.next()) {
            msgData<< query.value(0).toString();
            msgData<< query.value(1).toString();
            msgData<< query.value(2).toString();
            msgData<< query.value(3).toString();
    }

    // 提交事务
    db.commit();
    db.close();

    return msgData;
}

int fontheight(QString conText)
{
    QFont font;
    // 获取默认字体下文本的度量信息
    QFontMetrics metrics(font);
    int textHeight = metrics.height();//单个字体高度
    int count = conText.count("\n");// \n换行符数量
    int height = count * textHeight + count * 1 + 60;//实际设置item高度，文本内容宽度qlabel会自适应缩放
    return height;
}

QSize pixSize(QPixmap pix)
{
    int width = pix.width();
    int height = pix.height();
    qDebug() <<width;
    // 检查图片的宽度是否大于 400px 或者高度是否大于 300px
    while (width > 400 || height > 300) {
            // 若满足条件，将图片的宽度和高度缩小一倍
            width /= 2;
            height /= 2;
    }
    return QSize(width,height);
}

void saveMessageToDatabase(QString databaseName,const QString &msgId,const int &targetId,
                           const int &type,const int &media,const QString &content,
                           const double &createtime ,const double &readtime,const double &score)

{

    QSqlDatabase db;

    // 首先尝试获取已存在的连接
    if (QSqlDatabase::contains(databaseName)) {
            db = QSqlDatabase::database(databaseName);
            if (!db.open()) {
                qDebug() << "无法打开已存在的数据库连接saveMessageToDatabase:" << db.lastError().text();
                    return;
            }
    } else {
            // 连接不存在，添加新连接
            db = QSqlDatabase::addDatabase("QSQLITE", databaseName);
            QString databasePath = USER_PATH + "user.db";
            db.setDatabaseName(databasePath);
            if (!db.open()) {
                qDebug() << "无法打开新的数据库连接saveMessageToDatabase:" << db.lastError().text();
                    return;
            }
    }

    // 检查数据库连接是否打开
    if (!db.isOpen()) {
            qDebug() << "数据库连接未打开saveMessageToDatabase";
            return;
    }

    // 创建 messages 表（如果不存在）
    QString createMessagesTableQuery = "CREATE TABLE IF NOT EXISTS messages ("
                                       "msgId TEXT, "
                                       "TargetId INTEGER, "
                                       "Type INTEGER, "
                                       "Media INTEGER, "
                                       "Content TEXT, "
                                       "CreateTime REAL, "
                                       "ReadTime REAL, "
                                       "score REAL, "
                                       "PRIMARY KEY (msgId, score)"
                                       ")";
    QSqlQuery createTableQuery(db);
    if (!createTableQuery.exec(createMessagesTableQuery)) {
            qDebug() << "创建 messages 表失败saveMessageToDatabase:" << createTableQuery.lastError().text();
                                                        return;
    }

    // 插入数据的 SQL 查询，确保字段名与表结构一致
    QString insertQuery = "INSERT INTO messages (msgId, TargetId, Type, Media, Content, CreateTime, ReadTime, score) "
                          "VALUES (:msgId, :targetId, :type, :media, :content, :createtime, :readtime, :score)";
    QSqlQuery insertDataQuery(db);
    insertDataQuery.prepare(insertQuery);

    // 绑定参数
    insertDataQuery.bindValue(":msgId", msgId);
    insertDataQuery.bindValue(":targetId", targetId);
    insertDataQuery.bindValue(":type", type);
    insertDataQuery.bindValue(":media", media);
    insertDataQuery.bindValue(":content", content);
    insertDataQuery.bindValue(":createtime", createtime);
    insertDataQuery.bindValue(":readtime", readtime);
    insertDataQuery.bindValue(":score", score);

    // 执行插入查询
    if (!insertDataQuery.exec()) {
            qDebug() << "插入数据失败saveMessageToDatabase:" << insertDataQuery.lastError().text();
                                                 return;
    }

    //qDebug() << "数据插入成功";
}
